//
//  RCMerchantDishesViewController.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-10-1.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCMerchantDishesViewController.h"
#import "CommonDefines.h"
#import "UIColor-Expanded.h"
#import "NSString+NSString_Ex_.h"
#import "MBProgressHUD.h"
#import "IManager+ModuleMerchantPictureUpload.h"
#import "RCMerchantPhotoUploadDataModel.h"
#import "AppDelegate.h"
#import "NSArray+EX.h"
#import "GloableEngineService.h"

#define kBGimageFile        @"image_searchAllCity_cell_bg.png"
#define kLineImageFile      @"image_line_type3.png"
#define kInputImageFile     @"image_merchant_dish_input.png"
#define kRightButtonImageFile    @"image_merchant_commit_wrong_rightButton.png"
#define kHeaderBGimageFile  @"image_merchant_dishHeaderBG.png"

@interface RCMerchantDishesViewController ()<MBProgressHUDDelegate,IManagerDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property(nonatomic,retain)UITableView *dishTabelView;
@property(nonatomic,retain)RCMerchantPhotoUploadDataModel *dataModel;
@property(nonatomic,copy) NSString *shopID;
@property(nonatomic,copy) NSString *typeID;
@property(nonatomic,retain) MBProgressHUDEx *progressHub;
@property(nonatomic,assign) int64_t requestID;
@property(nonatomic,assign) UITextField *dishTextField;
@property(nonatomic,retain) UIButton *rightButton;

@end

@implementation RCMerchantDishesViewController

@synthesize dishTabelView = _dishTabelView;
@synthesize dataModel = _dataModel;
@synthesize shopID = _shopID;
@synthesize typeID = _typeID;
@synthesize progressHub = _progressHub;
@synthesize requestID = _requestID;
@synthesize delegate = _delegate;
@synthesize rightButton = _rightButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithMerchantID:(NSString *)shopID withTypeID:(NSString *)typeID{
    self = [super init];
    if (self) {
        self.shopID = shopID;
        self.typeID = typeID;
    }
    return self;
}

-(void)dealloc{
    
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
    self.delegate = nil;
    self.dishTabelView.delegate = nil;
    self.dishTabelView.dataSource = nil;
    self.dishTabelView = nil;
    self.dataModel = nil;
    self.shopID = nil;
    self.typeID = nil;
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.rightButton = nil;
    [super dealloc];
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IManager sharedInstance]cancelFetchDataRequestByRequestID:_requestID];
}

-(void)loadView{
    [super loadView];
    self.titleLabelText = @"菜名";
    self.navigationItem.titleView = [self createTitleView];
    
    _rightButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 0, 44, 44)];
    [_rightButton setImage:[UIImage imageNamed:kRightButtonImageFile]
                  forState:UIControlStateNormal];
    [_rightButton setImage:[UIImage imageNamed:kRightButtonImageFile]
                  forState:UIControlStateHighlighted];
    [_rightButton addTarget:self action:@selector(commitButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [self createRightBarButtonItemWithButton:_rightButton];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    _dishTabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, UIScreenHeight-64) style:UITableViewStylePlain];
    _dishTabelView.backgroundColor = [UIColor clearColor];
    _dishTabelView.dataSource = self;
    _dishTabelView.delegate = self;
    _dishTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.viewContainer addSubview:_dishTabelView];
    _dishTabelView.tableHeaderView = [self createTabelHeaderView];
    
    if ([GloableEngineService sharedInstance].netWorkStatus == kNotReachable) {
        return;
    }
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    
    _requestID = [[IManager sharedInstance]requestUploadPhotoCateforyInfoWithType:self.shopID withTypeID:self.typeID withDelegate:self];
}

-(UIImageView *)createTabelHeaderView{
    UIImageView *headerView = [[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 50)]autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    headerView.userInteractionEnabled = YES;
    UIImage *headImage =[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kHeaderBGimageFile ofType:nil]];
    headImage = [headImage resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
    [headerView setImage:headImage];
    UIImageView *inputView = [[UIImageView alloc]initWithFrame:CGRectMake(14, 11, 293, 28)];
    inputView.backgroundColor = [UIColor clearColor];
    inputView.userInteractionEnabled = YES;
    [inputView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kInputImageFile ofType:nil]]];
    _dishTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, 0, 200, 28)];
    _dishTextField.backgroundColor = [UIColor clearColor];
    _dishTextField.delegate = self;
    _dishTextField.textColor = [UIColor colorWithHex:0xffafafaf];
    _dishTextField.font = [UIFont fontWithName:kFontNameLightHeiti size:13];
    _dishTextField.textAlignment = UITextAlignmentLeft;
    _dishTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _dishTextField.placeholder = @"输入菜名";
    [_dishTextField setReturnKeyType:UIReturnKeyDone];
    [inputView addSubview:_dishTextField];
    
    
    [headerView addSubview:inputView];
    [inputView release];
    
    return headerView;
}

-(void)commitButtonClicked{
    if ([NSString stringIsNullOrEmpty:_dishTextField.text]) {
        [RCAppDelegate alertWithCustomizeString:@"请输入菜名或选择一个菜名"];
        return;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(selectDishedWithTypeName:withTypeID:)]) {
        [_delegate selectDishedWithTypeName:_dishTextField.text withTypeID:nil];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma -mark UITextFeildDelegate

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        
        RCMerchantPhotoUploadDataModel *typeDataModel = (RCMerchantPhotoUploadDataModel *)dataModel;
        self.dataModel = typeDataModel;
        [_dishTabelView reloadData];
    }
}

-(void)updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        [RCAppDelegate alertWithCustomizeString:@"数据加载错误，请稍后重试"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (nil == self.dataModel || nil == self.dataModel.itemListArray || [self.dataModel.itemListArray count] == 0) {
        return 0;
    }
    return [self.dataModel.itemListArray count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"RCDishTypeCell";
    RCMerchantDishesCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (nil == cell) {
        cell = [[[RCMerchantDishesCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease];
    }
    RCMerchantPhotoUploadItem *item = [self.dataModel.itemListArray safeObjectAtIndex:[indexPath row]];
    if (nil == item) {
        return nil;
    }
    [cell setcontentViewWithString:item.itemName];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    RCMerchantPhotoUploadItem *item = [self.dataModel.itemListArray safeObjectAtIndex:[indexPath row]];
    if (nil == item) {
        return;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(selectDishedWithTypeName:withTypeID:)]) {
        [_delegate selectDishedWithTypeName:item.itemName withTypeID:item.itemID];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

@implementation RCMerchantDishesCell

@synthesize contentLabel = _contentLabel;

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self.contentView setBackgroundColorWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kBGimageFile ofType:nil]]];
        _contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(14, 21, 200, 16)];
        _contentLabel.backgroundColor = [UIColor clearColor];
        _contentLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
        _contentLabel.textColor = [UIColor colorWithHex:0xff505050];
        [self addSubview:_contentLabel];
        UIImageView *lineImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 54, 320, 1)];
        [lineImageView setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kLineImageFile ofType:nil]]];
        [self addSubview:lineImageView];
        [lineImageView release];
        self.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    return self;
}

-(void)dealloc{
    self.contentLabel = nil;
    [super dealloc];
}

-(void)setcontentViewWithString:(NSString *)str{
    if ([NSString stringIsNullOrEmpty:str]) {
        return;
    }
    _contentLabel.text = str;
}


@end
